package com.sqoq.downloader3.retrofit

import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import org.json.JSONObject

/**
 * map转json
 *
 * @author dengmeng
 */
class ParameterMap : HashMap<String?, Any?>() {
    private fun toJson(map: ParameterMap): JSONObject {
        val jsonObject = JSONObject()
        try {
            for (key in map.keys) {
                val `val` = map[key]
                if (`val` is ParameterMap) {
                    jsonObject.put(key, toJson(`val`))
                } else {
                    jsonObject.put(key, `val`)
                }
            }
        } catch (e: Exception) {
        }
        return jsonObject
    }

    fun toJson(): JSONObject {
        return toJson(this)
    }

    fun toJsonString(): String {
        return toJson().toString()
    }

    fun toRequestBody(): RequestBody {
        var requestBody = RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(), toJsonString());
        return requestBody
    }
}